import { defineStore } from "pinia";
import { ref } from "vue";

export const useHistoryStore = defineStore(
  "useHistoryStore",
  () => {
    const historyList = ref<string[]>([]);

    function getHistoryHistory() {
      return historyList.value;
    }

    //添加历史查看记录
    function addHistory(id: string) {
      if (!id) return;
      const index = historyList.value.indexOf(id);
      //判断是否已经用
      if (index !== -1) {
        //有就删除
        historyList.value.splice(index, 1);
      }
      //添加历史记录，保持置顶
      historyList.value.unshift(id);
    }

    //删除历史搜索记录
    function delHistory(id: string) {
      const index = historyList.value.indexOf(id);
      historyList.value.splice(index, 1);
    }

    //删除所有历史记录
    function delAllHistory() {
      historyList.value = [];
    }

    return {
      historyList,
      getHistoryHistory,
      addHistory,
      delHistory,
      delAllHistory,
    };
  },

  {
    //开启持久化
    persist: {
      key: "yx:shopping:history",
    },
  }
);
